package cn.aixuegao.service.admin.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import cn.aixuegao.model.admin.Column;
import cn.aixuegao.model.user.User;
import cn.aixuegao.service.admin.ColumnService;
import cn.aixuegao.common.base.service.impl.BaseService;
import cn.aixuegao.dao.admin.ColumnDAO;

/**
* 描述：栏目 服务实现层
* @author hxy
* @date 2018/04/28
*/
@Service("ColumnService")
public class ColumnServiceImpl  extends BaseService<ColumnDAO,Column> implements ColumnService{

	@Autowired
	ColumnDAO columnDAO;

	@Override
	public List<Column> getColumnTree(User user) {
		EntityWrapper<Column> ew = new EntityWrapper<Column>(new Column(user.getId()));
		//获取所有栏目的数据
		List<Column> columnList = columnDAO.selectList(ew);
		//保存最后的结果
		List<Column> columnTreeList = new ArrayList<Column>();
		// 先找到所有的一级菜单
	    for (int i = 0; i < columnList.size(); i++) {
	        // 一级菜单没有parentId
	        if (0 == columnList.get(i).getPid()) {
	        	columnTreeList.add(columnList.get(i));
	        }
	    }
	    // 为一级菜单设置子菜单，getChild是递归调用的
	    for (Column column : columnList) {
	    	column.setChildren(getChild(column.getId(), columnList));
	    }
		return columnTreeList;
	}
	
    
	/**
	 * 
	 * @Title:ColumnServiceImpl
	 * @Description:递归查找子栏目
	 * @param id
	 * @param columnList
	 * @return
	 */
	private List<Column> getChild(Integer id, List<Column> columnList) {
	    // 子菜单
	    List<Column> childList = new ArrayList<>();
	    for (Column column : columnList) {
	        // 遍历所有节点，将父菜单id与传过来的id比较
	        if (0 != column.getPid()) {
	            if (column.getPid().equals(id)) {
	                childList.add(column);
	            }
	        }
	    }
	    // 把子菜单的子菜单再循环一遍
	    /*for (Column column : childList) {// 没有url子菜单还有子菜单
	        if (StringUtils.isBlank(column.getUrl())) {
	            // 递归
	        	column.setChildren(getChild(column.getId(), columnList));
	        }
	    }*/
	    // 递归退出条件
	    if (childList.size() == 0) {
	        return null;
	    }
	    return childList;
	}
    

}


	

